package com.aluka.nirvana.framework.core.handler;

import com.aluka.nirvana.framework.core.exception.BaseException;
import com.aluka.nirvana.framework.core.exception.BusinessException;
import com.aluka.nirvana.framework.core.exception.CommonErrors;
import com.aluka.nirvana.framework.core.exception.UnknownException;
import com.aluka.nirvana.framework.core.model.ResponseBaseEntity;
import com.google.common.base.Throwables;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

/**
 * 控制层异常拦截
 * @author gongli
 * @since 2019/12/25
 */
@ControllerAdvice
@Slf4j
public class ControllerExceptionHandler {

    public ControllerExceptionHandler() {}


    @ExceptionHandler({BusinessException.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseBaseEntity handleBusinessException(BaseException exception) {
        log.error(">>Nirvana<< BusinessException: ", Throwables.getRootCause(exception));
        return ResponseBaseEntity.error(exception.getMessage(),exception);
    }



    @ExceptionHandler({Exception.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseBaseEntity handleException(Exception exception) {
        log.error(">>Nirvana<< Unknown Exception:", Throwables.getRootCause(exception));
        UnknownException e = new UnknownException(CommonErrors.SYSTEM_ERROR, "", exception);
        return ResponseBaseEntity.error(exception.getMessage(),e);
    }

    @ExceptionHandler({Throwable.class})
    @ResponseStatus(HttpStatus.OK)
    @ResponseBody
    public ResponseBaseEntity handleException(Throwable t) {
        log.error(">>Nirvana<< Unknown Throwable:", Throwables.getRootCause(t));
        UnknownException e = new UnknownException(CommonErrors.SYSTEM_ERROR, "", t);
        return ResponseBaseEntity.error(t.getMessage(),e);
    }
}